import React from 'react';
import {
  Row,
  Col,
  Tree,
  Select,
  Button,
  Input,
  Form,
  DatePicker,
  Spin,
  Table,
  Pagination,
  TreeSelect,
  message,
  Modal
} from 'antd';
const { confirm } = Modal;
import {
  SearchOutlined,
  PlusOutlined,
  EditOutlined,
  SyncOutlined,
  UserOutlined,
  CloseOutlined,
} from '@ant-design/icons';
// import { Page } from 'components'
import styles from './index.less';
import { connect } from 'dva';

import AddModal from './addModal';
// import RoleModal from './roleModal';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import _ from 'lodash'
import defaultSettings from '@ant-design/pro-layout/lib/defaultSettings';

import defaultSetting from '../../../../config/defaultSettings'

@Form.create()
@connect(({ system }) => ({ ...system }))
class Index extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      currSystemId: '',
      currAuthName: '',
      currUrl: '',
      currSystemName: '',
      timestamp: '',
      checkColumns: [
        { title: '权限名称', dataIndex: 'authName', key: 'authName' },
        { title: '权限编码', dataIndex: 'authCode', key: 'authCode' },
        { title: '权限类型', dataIndex: 'authTypeDesc', key: 'authTypeDesc' },
        { title: '权限样式', dataIndex: 'modelStyle', key: 'modelStyle' },
        { title: 'URL', dataIndex: 'url', key: 'url' },
        { title: '顺序', dataIndex: 'dispOrder', key: 'dispOrder' },
        { title: '版本', dataIndex: 'version', key: 'version' },
        {
          title: '操作',
          dataIndex: 'cz',
          width: 200,
          render: (text, record) => (
            <p className={styles.tableBtns}>
              <a onClick={() => this.addFun(record.authId)}>
                <PlusOutlined />
                新增
              </a>
              <a onClick={() => this.updateData(record)}>
                <EditOutlined />
                修改
              </a>
              <a onClick={() => this.deleteData(record)}>
                <CloseOutlined />
                删除
              </a>
            </p>
          ),
        },
      ],
      dataList: [],
      totalPage: 1,
      totalData: 1,
      currentPage: 1,
      loading: false,
      // selectedRowKeys: [],
      addModalVisible: false,
      addTimestamp: Date.parse(new Date()),
      addLoading: false,

      systemNameList: [],

      tableData: [],

      roleTimestamp: Date.parse(new Date()),
      roleModalVisible: false,
      roleLoading: false,
      authDetail: {}, //当前用户详情
      currRoleName: '',
      pwdVisible: false,
      currPwdTitle: '',
      resetPwdLoading: false
    };
  }

  componentDidMount() {
    this.init();
  }

  init = () => {
    this.querySystemNameList();
  };

  //获取用户列表
  querySever = async () => {
    this.setState({ loading: true });
    const { props } = this;
    await props
      .dispatch({
        type: 'system/queryMenuList',
        payload: {
          authName: this.state.currAuthName,
          url: this.state.currUrl,
          systemId: this.state.currSystemId,
          page: this.state.currentPage,
          rows: 10,
        },
      })
      .then(res => {
        this.setState({
          loading: false,
          totalData: res.length,
        });
        // let tempArray;
        if(this.state.currAuthName==''&&this.state.currUrl==''){
          let parents = res.filter(
            value => value.parentId == 0 || value.parentId == null
          );
          let childrens = res.filter(
            value => value.parentId !== 0 && value.parentId != null
          );
          for(let i=0;i<res.length;i++){
            res[i].key = res[i].authId
          }
          this.setState({
            dataList: this.toTreeData(parents, childrens),
            timestamp: Date.parse(new Date()) + 1,
          });
        }else{
          this.setState({
            dataList: res?res:[],
            timestamp: Date.parse(new Date()) + 1,
          });
        }
        console.log(this.state.dataList, 'haha');
      });
  };

  fliterEvent= (parents, childrens) => {
    parents.forEach(parent => {
      childrens.forEach((current, index) => {
        if (current.parentId === parent.authId) {
          let temp = JSON.parse(JSON.stringify(childrens));
          temp.splice(index, 1);
          this.fliterEvent([current], temp);
          typeof parent.children !== "undefined"
            ? parent.children.push(current)
            : (parent.children = [current]);
        }
      });
    });
  };

  toTreeData = (parents,childrens)=>{
      this.fliterEvent(parents, childrens);
      return parents;
  }
  
  querySystemNameList = async () => {
    const { props } = this;
    await props
      .dispatch({
        type: 'system/systemNameListPost',
        payload: {
          page: 1,
          rows: 20,
        },
      })
      .then(res => {
        if(res['list']){
          this.setState({
            systemNameList: res.list ? res.list : [],
            currSystemId: (defaultSetting.systemId&&defaultSetting.systemId!='')?defaultSetting.systemId: (res.list? res.list[0].systemId : ''),
            currSystemName: res.list?res.list[0].systemName: ''
          },()=>{
            this.querySever();
          });
        }else{
          message.error(res.msg)
        }
      });
  };

  //系统名称修改
  systemIdChange = value => {
    this.setState({
      currSystemId: value,
    });
    const { systemNameList } = this.state;
    for(let i=0;i<systemNameList.length;i++){
      if(value == systemNameList[i].systemId){
        this.setState({
          currSystemName: systemNameList[i].systemName
        })
      }
    }
  };

  //权限名称修改
  authNameChange = e => {
    this.setState({
      currAuthName: e.target.value,
    });
  };

  //URL修改
  urlChange = e => {
    this.setState({
      currUrl: e.target.value,
    });
  };

  //提交订单
  submitFun = () => {
    this.init();
  };

  //重置
  resetFun = () => {
    this.setState(
      {
        currSystemId: '',
        currAuthName: '',
        currUrl: '',
        timestamp: Date.parse(new Date()) + 1,
      },
      () => {
        this.init();
      },
    );
  };

  //修改信息
  updateData = record => {
    this.setState({
      authDetail: record,
      addModalVisible: true,
      addTimestamp: Date.parse(new Date()) + 1,
    });
  };

  //删除信息
  deleteData = record => {
    const _this = this;
    confirm({
      // icon: <ExclamationCircleOutlined />,
      content: `确认删除【${record.authName}】?`,
      onOk() {
        console.log('OK');
        const { dispatch } = _this.props;
        dispatch({
          type: 'system/deleteMenuPost',
          payload: {
            authId: record.authId
          },
        }).then(res => {
          if(res.success){
            if (res.code == 0) {
              message.success('删除成功！');
            } else {
              message.error(res.msg);
            }
            _this.init()
          }else {
            message.error(res.msg);
          }
        });
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }

  pageChange = page => {
    this.setState(
      {
        currentPage: page,
      },
      () => {
        this.init();
      },
    );
  };

  get addModalProps() {
    const { addModalVisible, authDetail, addLoading } = this.state;
    let _this = this;
    return {
      title: '菜单管理',
      visible: addModalVisible,
      authDetail: authDetail,
      loading: addLoading,
      width: '700px',
      okText: '提交',
      cancelText: '取消',
      onOk: data => {
        console.log(data,'data')
        _this.setState(
          {
            loading: true,
          },
          () => {
            const { dispatch } = _this.props;
            dispatch({
              type: data.authId==''?'system/addMenuPost':'system/editMenuPost',
              payload: Object.assign({},authDetail,data),
            }).then(res => {
              if(res.success){
                if (res.code == 0) {
                  message.success(data.authId==''?'新增成功！':'修改成功！');
                } else {
                  message.error(res.msg);
                }
                _this.setState(
                  {
                    loading: false,
                    addModalVisible: false,
                  },
                  () => {
                    _this.init();
                  },
                );
              }else {
                message.error(res.msg);
              }
            });
          },
        );
      },
      onCancel() {
        _this.setState({
          addModalVisible: false,
        });
      },
    };
  }

  //新增用户
  addFun = (parentId) => {
    this.setState({
      authDetail: {
        authId: '',
        systemId: this.state.currSystemId,
        systemName: this.state.currSystemName,
        parentId: parentId,
        authCode: '00',
        authName: '',
        authType: 'expand',
        modelStyle: '',
        url: '',
        dispOrder: '',
        remark: ''
      },
      addModalVisible: true,
      addTimestamp: Date.parse(new Date()) + 1,
    });
  };

  render() {
    const { checkColumns, dataList, addTimestamp, roleTimestamp, systemNameList, timestamp } = this.state;

    const { getFieldDecorator } = this.props.form;

    // const rowSelection = {
    //   selectedRowKeys,
    //   onChange: this.onSelectChange,
    // };
    return (
      <PageHeaderWrapper title={false} breadcrumb={false}>
      <div className={styles.mainPage}>
        <Row>
          <Col span={24}>
            <dl key={timestamp+1}>
              <dt>
                <Form name="horizontal_search" layout="inline">
                  {
                    (!defaultSetting.systemId||defaultSetting.systemId=='')&&
                    <Form.Item name="systemId" label="系统名称">
                      <Select
                        style={{ width: 200 }}
                        placeholder="请选择系统名称"
                        onChange={this.systemIdChange}
                        value={this.state.currSystemId}
                      >
                        {
                          systemNameList.map(item=>{
                            return(<Option value={item.systemId}>{item.systemName}</Option>)
                          })
                        }
                      </Select>
                    </Form.Item>
                  }
                  <Form.Item name="authName" label="权限名称">
                    <Input
                      style={{ width: 200 }}
                      type="text"
                      placeholder="请输入名称搜索"
                      defaultValue={this.state.currAuthName}
                      onChange={this.authNameChange}
                    />
                  </Form.Item>
                  <Form.Item name="url" label="URL">
                    <Input
                      style={{ width: 200 }}
                      type="text"
                      placeholder="请输入URL"
                      defaultValue={this.state.currUrl}
                      onChange={this.urlChange}
                    />
                  </Form.Item>
                  <Form.Item>
                    <Button type="primary" onClick={this.submitFun}>
                      <SearchOutlined />
                      搜索
                    </Button>
                    <Button style={{ marginLeft: '8px' }} onClick={this.resetFun}>
                      <SyncOutlined />
                      重置
                    </Button>
                  </Form.Item>
                  <Form.Item style={{ float: 'right', marginRight: 0 }}>
                    <Button type="primary" onClick={()=>this.addFun(0)}>
                      <PlusOutlined />
                      新增
                    </Button>
                  </Form.Item>
                </Form>
              </dt>
              <dd>
                <AddModal key={addTimestamp} {...this.addModalProps} />
                <Spin spinning={this.state.loading} delay={500}>
                  {
                    this.state.currAuthName==''&&this.state.currUrl==''?
                    <Table
                      style={{ marginTop: '20px' }}
                      bordered
                      columns={checkColumns}
                      dataSource={dataList}
                      simple
                      // scroll={{ x: 1200 }}
                      pagination={false}
                      // rowSelection={rowSelection}
                    />:<Table
                      style={{ marginTop: '20px' }}
                      bordered
                      columns={checkColumns}
                      // expandable={{
                      //   expandedRowRender: record => <p style={{ margin: 0 }}>{record.description}</p>,
                      //   rowExpandable: record => record.name !== 'Not Expandable',
                      // }}
                      dataSource={dataList}
                      pagination={false}
                    />
                  }
                </Spin>
                {/* <p style={{ textAlign: 'center', marginTop: '20px' }}>
                  <Pagination
                    current={this.state.currentPage}
                    total={this.state.totalData}
                    onChange={this.pageChange}
                  />
                </p> */}
              </dd>
            </dl>
          </Col>
        </Row>
      </div>
      </PageHeaderWrapper>
    );
  }
}

export default Index;
